package com.dt.handler;

import com.alibaba.fastjson.JSON;
import com.dt.base.MsgTypeConstant;
import com.dt.base.WebSocketConstant;
import com.dt.dto.TextMessageDto;
import com.dt.service.WebSocketService;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.*;
import lombok.extern.slf4j.Slf4j;

/**
 * @Auther: dengtao
 * @Date: 2019/11/25 11:13
 * @Description:
 */
@Slf4j
public class WebSocketHandler extends SimpleChannelInboundHandler<WebSocketFrame> {

    private WebSocketServerHandshaker handshaker;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame msg) throws Exception {
        log.info("收到消息："+msg);
        //处理websocket客户端的消息
        handlerWebSocketFrame(ctx,msg);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //添加连接
        log.info("客户端加入连接："+ctx.channel());
        //ChannelSupervise.addChannel(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        //断开连接
        log.info("客户端断开连接："+ctx.channel());
        WebSocketService.removeChannel(ctx.channel());
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }


    private void handlerWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame){
        // 判断是否关闭链路的指令
        if (frame instanceof CloseWebSocketFrame) {
            handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
            return;
        }
        // 判断是否ping消息
        if (frame instanceof PingWebSocketFrame) {
            ctx.channel().write(
                    new PongWebSocketFrame(frame.content().retain()));
            return;
        }
        // 本例程仅支持文本消息，不支持二进制消息
        if (!(frame instanceof TextWebSocketFrame)) {
            log.info("本例程仅支持文本消息，不支持二进制消息");
            throw new UnsupportedOperationException(String.format(
                    "%s frame types not supported", frame.getClass().getName()));
        }
        // 返回应答消息
        String request = ((TextWebSocketFrame) frame).text();
        log.info("服务端收到：" + request);
        TextMessageDto textMessageDto = JSON.parseObject(request, TextMessageDto.class);

        this.dealWithMessage(textMessageDto,ctx.channel());

    }


    public void dealWithMessage(TextMessageDto textMessageDto, Channel channel){

        switch (textMessageDto.getType()){
            case MsgTypeConstant.LOGIN_MESSAGE:
                WebSocketService.addChannel(textMessageDto,channel);
                break;
            case MsgTypeConstant.SEND_ME_MESSAGE:
                WebSocketService.sendToMe(textMessageDto,channel);
                break;
            case MsgTypeConstant.SEND_OTHER_MESSAGE:
                WebSocketService.sendToOther(textMessageDto);
                break;
            case MsgTypeConstant.SEND_ALL_MESSAGE:
                WebSocketService.sendToAll(textMessageDto);
                break;
        }

    }



}
